package com.situ.mall.controller;

import com.situ.imall.util.ImageServerUtil;
import com.situ.imall.util.JSONResult;
import com.situ.imall.util.QiniuUtils;
import com.situ.imall.util.RedisConstant;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName UploadController
 * @Description 上传相关操作
 * @Author 周轩霆
 * @Date 2022/8/23 9:30
 **/
@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/uploadImage")
    @ResponseBody
    public JSONResult uploadImage(MultipartFile file) {
        String name = UUID.randomUUID().toString().replace("-", "");
        String filename = file.getOriginalFilename();
        //D:/mypic/a.jpg
        String extension = FilenameUtils.getExtension(filename);//拿到后缀 .jpg
        String newFileName = name + "." + extension;
        //本地还是七牛云？
        if (ImageServerUtil.IMG_SERVER == ImageServerUtil.LOCAL) {

            String filePath = "D:\\mypic\\" + newFileName;
            try {
                file.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                QiniuUtils.upload2Qiniu(file.getBytes(), newFileName);
                //开启定时任务
                //上传图片名字到Redis Set集合 方便和添加部分的set进行对比 清除垃圾图片
                redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE, newFileName);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE, newFileName);
        return JSONResult.ok("上传成功！", newFileName);
    }

    public static void main(String[] args) {
        String s = UUID.randomUUID().toString();
        System.out.println(s.replace("-", ""));
    }
}
